package tech.summerly.weather.component.viewmodel

import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import tech.summerly.weather.data.local.RegionDataBase
import tech.summerly.weather.model.Region

class RegionViewModel : ViewModel() {


    /**
     * 搜索结果
     * List<Region>为区域列表
     * String为关键词
     */
    val searchResult = MutableLiveData<Pair<List<Region>, String>>()

    companion object : ViewModelProvider.Factory {

        private val model by lazy { RegionViewModel() }

        @Suppress("UNCHECKED_CAST")
        override fun <T : ViewModel?> create(modelClass: Class<T>): T = model as T

    }

    private val regionDao = RegionDataBase.INSTANCE.regionDao()

    fun getAllRegion() = regionDao.getRegions()

    /**
     * 使用 [searchResult] 来监听搜索结果
     */
    fun searchRegion(query: String) {
        searchResult.postValue(regionDao.queryRegion(query) to query)
    }

}